<template>
    <div class="course-form">
        <h2>{{ editingCourse ? '编辑课程' : '添加新课程' }}</h2>
        <form @submit.prevent="handleSubmit">
            <div class="form-group">
                <label for="name">课程名称：</label>
                <input type="text" id="name" v-model="formData.name" required>
            </div>
            <div class="form-group">
                <label for="teacher">授课教师：</label>
                <input type="text" id="teacher" v-model="formData.teacher" required>
            </div>
            <div class="form-group">
                <label for="credit">学分：</label>
                <input type="number" id="credit" v-model.number="formData.credit" min="1" max="10" required>
            </div>
            <button type="submit">{{ editingCourse ? '更新' : '添加' }}</button>
            <button type="button" @click="resetForm" v-if="editingCourse">取消</button>
        </form>
    </div>
</template>

<script setup>
import { ref, watch } from 'vue';

// 定义props
const props = defineProps({
    editingCourse: Object
});

// 定义表单数据
const formData = ref({
    name: '',
    teacher: '',
    credit: 1
});

// 定义emits
const emit = defineEmits(['submit', 'cancel']);

// 提交表单
const handleSubmit = () => {
    emit('submit', formData.value);
    if (!props.editingCourse) {
        resetForm();
    }
};

// 重置表单
const resetForm = () => {
    formData.value = {
        name: '',
        teacher: '',
        credit: 1
    };
    emit('cancel');
};

// 监听编辑课程的变化
watch(() => props.editingCourse, (newVal) => {
    if (newVal) {
        formData.value = { ...newVal };
    } else {
        resetForm();
    }
}, { immediate: true });
</script>

<style scoped>
.course-form {
    margin-bottom: 2rem;
    padding: 1rem;
    border: 1px solid #ddd;
    border-radius: 4px;
}

.form-group {
    margin-bottom: 1rem;
}

label {
    display: block;
    margin-bottom: 0.5rem;
}

input {
    width: 100%;
    padding: 0.5rem;
    border: 1px solid #ddd;
    border-radius: 4px;
}

button {
    margin-right: 0.5rem;
    padding: 0.5rem 1rem;
    background-color: #42b983;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

button:hover {
    background-color: #369f6b;
}
</style>